<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['project:info:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['project:info:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['project:info:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['project:info:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="id" align="center" prop="projectId" /> -->
      <el-table-column label="排序" align="center" prop="orderNum" />
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="项目内容" align="center" prop="projectInfo" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180" />
      <el-table-column label="截至日期" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目负责人" align="center" prop="chargeName" />
      <!-- 0未开始1进行中2暂停3结束 -->
      <el-table-column label="状态" align="center" prop="state">
        <template #default="scope">
          <el-button link type="primary" v-if="scope.row.state == '0'" @click="handleStart(scope.row)">未开始</el-button>
          <el-button link type="primary" v-if="scope.row.state == '1'" @click="handlePause(scope.row)">进行中</el-button>
          <el-button link type="primary" v-if="scope.row.state == '2'" @click="handleStart(scope.row)">暂停</el-button>
          <span link type="primary" v-if="scope.row.state == '3'">完成</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['project:info:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['project:info:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改项目信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="infoRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目内容" prop="projectInfo">
          <el-input v-model="form.projectInfo" placeholder="请输入项目内容" />
        </el-form-item>
        <el-form-item label="显示排序" prop="orderNum">
          <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="form.state" placeholder="请选择项目状态" clearable>
            <el-option v-for="item in stateOption" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="截至日期" prop="endTime">
          <el-date-picker style="width: 100%;" clearable v-model="form.endTime" type="date"
            value-format="YYYY-MM-DD hh:mm:ss" placeholder="请选择截至日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="项目负责人" prop="chargeId">
          <span style="width: 70%;">{{ form.chargeName }}</span>
          <el-button type="primary" icon="User" @click="handleOpenSelectUser">选择用户</el-button>
        </el-form-item>

        <el-form-item label="项目人员" prop="userIdList">
          <el-select multiple v-model="form.userIdList" placeholder="请选择人员" clearable @change="handleProjectChange">
            <el-option v-for="user in userList" :key="user.userId" :label="user.nickName" :value="user.userId" />
          </el-select>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 选人dialog -->
    <el-dialog :title="选择项目负责人" v-model="userOpen" width="500px" append-to-body>
      <el-table :data="userList" @row-click="handleSelectUser">
        <el-table-column label="id" align="center" prop="userId" />
        <el-table-column label="部门" align="center" prop="dept.deptName" />
        <el-table-column label="姓名" align="center" prop="nickName" />
      </el-table>
      <pagination v-show="user_total > 0" :total="user_total" v-model:page="userQueryParams.pageNum"
        v-model:limit="userQueryParams.pageSize" @pagination="getUserList" />
    </el-dialog>
  </div>
</template>

<script setup name="Info">
import { listProjectInfo, getProjectInfo, delProjectInfo, addProjectInfo, updateProjectInfo } from "@/api/task/project";
import { listUser } from "@/api/system/user";
const { proxy } = getCurrentInstance();
import { parseTime } from "@/utils/ruoyi";

const infoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
// 选择用户 user_total
const userList = ref([]);
const user_total = ref(0);
const userOpen = ref(false);

//项目状态 0未开始1进行中2暂停3结束
const stateOption = ref([{
  name: '未开始',
  value: '0',
}, {
  name: '进行中',
  value: '1',
}, {
  name: '暂停',
  value: '2',
}, {
  name: '结束',
  value: '3',
}]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    timeoutState: null
  },
  userQueryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    projectName: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
    projectInfo: [{ required: true, message: "项目内容不能为空", trigger: "blur" }],
    chargeId: [{ required: true, message: "项目负责人不能为空", trigger: "blur" }],
    orderNum: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
    endTime: [{ required: true, message: "截至日期不能为空", trigger: "blur" }]
  }
});

const { queryParams, userQueryParams, form, rules } = toRefs(data);

/** 查询项目信息列表 */
function getList() {
  loading.value = true;
  listProjectInfo(queryParams.value).then(response => {
    infoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    projectId: null,
    projectName: null,
    projectInfo: null,
    endTime: null,
    chargeId: null,
    chargeName: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
    delFlag: null,
    timeoutState: null
  };
  proxy.resetForm("infoRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.projectId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加项目信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _projectId = row.projectId || ids.value
  getProjectInfo(_projectId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改项目信息";
  });
}



/** 开始项目 */
function handleStart(row) {
  const projectId = row.projectId
  getProjectInfo(projectId).then(response => {
    form.value = response.data;
    form.value.state = "1";
    form.value.startTime = parseTime(new Date());
  }).then(() => {
    updateProjectInfo(form.value).then(response => {
      proxy.$modal.msgSuccess("开始成功");
      getList();
    });
  });
}
/** 暂停项目 */
function handlePause(row) {
  const projectId = row.projectId
  getProjectInfo(projectId).then(response => {
    form.value = response.data;
    if (form.value.state == "0") {
      proxy.$modal.msgError("项目未开始，无法暂停");
      reject(new Error('项目未开始，无法暂停'));
    }
    if (form.value.state == "3") {
      proxy.$modal.msgError("项目已结束无法暂停");
      reject(new Error('项目已结束无法暂停'));
    }
    form.value.state = "2";
  }).then(() => {
    updateProjectInfo(form.value).then(response => {
      proxy.$modal.msgSuccess("暂停成功");
      getList();
    });
  });;
}

function handleFinish(row) {
  if (row.state == "3") {
    proxy.$modal.msgError("项目已完成，请勿重复操作");
    return;
  }
  if (row.state == "0") {
    proxy.$modal.msgError("项目未开始，无法完成");
    return;
  }
  const _taskId = row.taskId || ids.value
  proxy.$modal.confirm('是否确认完成项目？').then(function () {
    return getInfo(_taskId).then(response => {
      form.value = response.data;
      form.value.state = "3";
      form.value.endTime = parseTime(new Date());
    })
  }).then(() => {
    updateProjectInfo(form.value).then(response => {
      proxy.$modal.msgSuccess("项目完成成功");
      getList();
    });
  }).catch(() => { });
}


/** 提交按钮 */
function submitForm() {
  proxy.$refs["infoRef"].validate(valid => {
    if (valid) {
      if (form.value.projectId != null) {
        // 项目人员
        console.log("======" + form.value.userIdList);
        form.value.peopleIds = JSON.stringify(form.value.userIdList);
        console.log("======" + form.value.peopleIds);
        updateProjectInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        // 项目人员
        console.log("======" + form.value.userIdList);
        form.value.peopleIds = JSON.stringify(form.value.userIdList);
        console.log("======" + form.value.peopleIds);
        addProjectInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _projectIds = row.projectId || ids.value;
  proxy.$modal.confirm('是否确认删除项目信息编号为"' + _projectIds + '"的数据项？').then(function () {
    return delProjectInfo(_projectIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('project/info/export', {
    ...queryParams.value
  }, `info_${new Date().getTime()}.xlsx`)
}

//==========================================================
/** 查询用户列表 */
function getUserList() {
  listUser(proxy.addDateRange(userQueryParams.value)).then(res => {
    userList.value = res.rows;
    user_total.value = res.total;
  });
};

function handleOpenSelectUser() {
  userOpen.value = true;
  getUserList();
};


function handleSelectUser(row) {
  userOpen.value = false;
  console.log(row);
  form.value.chargeId = row.userId;
  form.value.chargeName = row.nickName;
};

//
getList();
//
getUserList();
</script>
